package com.moxiao.yfjh.module.system.sms.utils;

import com.moxiao.yfjh.framework.common.util.json.JsonUtils;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jsms.api.SendSMSResult;
import cn.jsms.api.ValidSMSResult;
import cn.jsms.api.common.SMSClient;
import cn.jsms.api.common.model.SMSPayload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @version 1.0
 * @Author zhk
 * @Date 2023/11/10 13:54
 **/
public class JSMSExampleUtil {

    protected static final Logger LOG = LoggerFactory.getLogger(JSMSExampleUtil.class);
    private static final String appkey = "53ae66c14ab0234bbd26367f";//242780bfdd7315dc1989fe2b
    private static final String masterSecret = "d00bafb4838ddb8d45093a3e";//2f5ced2bef64167950e63d13

    /** 极光 医养云-医生端 AppKey **/
    private static final String appkey_yangyun = "51a7bd6b970c38f24a8fbc49";
    private static final String masterSecret_yangyun = "386fce73651c209022a2c598";
    private static final Integer MSID= 208765;

    /**
     * 发送短信验证码
     * @param mobile
     */
    public static String testSendSMSCode(String mobile) {
        String appkey = JSMSExampleUtil.appkey;
        String masterSecret  = JSMSExampleUtil.masterSecret;
        SMSClient client = new SMSClient(masterSecret, appkey);
        String msg_id="";
        SMSPayload payload = SMSPayload.newBuilder()
                .setMobileNumber(mobile)
                .setTempId(1)
                .build();
        try {
            SendSMSResult res = client.sendSMSCode(payload);//{"msg_id":"669857824992"}
            System.out.println(res.toString());
            msg_id = res.getMessageId();
        } catch (APIConnectionException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        } catch (APIRequestException e) {
            System.out.println(e.getStatus() + " errorCode: " + e.getErrorCode() + " " + e.getErrorMessage());
        }
        return msg_id;
    }


    /*
     * 验证码校验{"is_valid":true}
     */
    public static boolean testSendValidSMSCode(String msg_id,String valid) {
        String appkey = JSMSExampleUtil.appkey;
        String masterSecret  = JSMSExampleUtil.masterSecret;
        SMSClient client = new SMSClient(masterSecret, appkey);
        boolean result=false;
        try {
//			ValidSMSResult res = client.sendValidSMSCode("01658697-45d9-4644-996d-69a1b14e2bb8", "556618");
            ValidSMSResult res = client.sendValidSMSCode(msg_id, valid);
            System.out.println(res.toString());
            result=res.getIsValid();
        } catch (APIConnectionException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        } catch (APIRequestException e) {
            if (e.getErrorCode() == 50010) {
                // do something
            }
            System.out.println(e.getStatus() + " errorCode: " + e.getErrorCode() + " " + e.getErrorMessage());
        }
        return result;
    }


    // 测试短信送达状态回调
    public static void url1() {
        long nonce = new Random().nextLong();
        long timestamp = System.currentTimeMillis();
        String str = String.format("appKey=%s&appMasterSecret=%s&nonce=%s&timestamp=%s",
                appkey, masterSecret, nonce, timestamp);
        String signature = encrypt(str);
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("nonce", nonce);
        params.put("timestamp", timestamp);
        params.put("signature", signature);

        ReportMessage reportMessage = new ReportMessage();
        reportMessage.setMsgId("1652496");
        reportMessage.setStatus(4001);
        reportMessage.setPhone("15822889320");
        reportMessage.setReceiveTime(new Date());
        params.put("data", JsonUtils.toJsonString(reportMessage));
        params.put("type", "SMS_REPORT");
        System.out.println("post params: " + JsonUtils.toJsonString(params));
//	    sendPost(URL, params);
    }
    private static class ReportMessage {
        private String msgId;
        private Integer status;
        private String phone;
        private Date receiveTime;

        public String getMsgId() {
            return msgId;
        }
        public void setMsgId(String msgId) {
            this.msgId = msgId;
        }
        public Integer getStatus() {
            return status;
        }
        public void setStatus(Integer status) {
            this.status = status;
        }
        public String getPhone() {
            return phone;
        }
        public void setPhone(String phone) {
            this.phone = phone;
        }
        public Date getReceiveTime() {
            return receiveTime;
        }
        public void setReceiveTime(Date receiveTime) {
            this.receiveTime = receiveTime;
        }
    }

    /**
     * SHA1加密
     *
     * @param strSrc 明文
     * @return 加密之后的密文
     */
    public static String encrypt(String strSrc) {
        MessageDigest md = null;
        String strDes = null;
        byte[] bt = strSrc.getBytes();
        try {
            md = MessageDigest.getInstance("SHA-1");// 将此换成SHA-1、SHA-512、SHA-384等参数
            md.update(bt);
            strDes = bytes2Hex(md.digest()); // to HexString
        } catch (NoSuchAlgorithmException e) {
            return null;
        }
        return strDes;
    }

    /**
     * byte数组转换为16进制字符串
     *
     * @param bts 数据源
     * @return 16进制字符串
     */
    private static String bytes2Hex(byte[] bts) {
        String des = "";
        String tmp = null;
        for (int i = 0; i < bts.length; i++) {
            tmp = (Integer.toHexString(bts[i] & 0xFF));
            if (tmp.length() == 1) {
                des += "0";
            }
            des += tmp;
        }
        return des;
    }

    /**
     * 根据模板发送短信验证码
     * @param mobile
     */
    public static String sendSMSTemp(String mobile) {
        String appkey = JSMSExampleUtil.appkey_yangyun;
        String masterSecret  = JSMSExampleUtil.masterSecret_yangyun;
        SMSClient client = new SMSClient(masterSecret, appkey);
        String msg_id="";
        SMSPayload payload = SMSPayload.newBuilder()
                .setMobileNumber(mobile)
                .setTempId(MSID)
                .build();
        try {
            SendSMSResult res = client.sendTemplateSMS(payload);
            System.out.println(res.toString());
            msg_id = res.getMessageId();
        } catch (APIConnectionException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        } catch (APIRequestException e) {
            System.out.println(e.getStatus() + " errorCode: " + e.getErrorCode() + " " + e.getErrorMessage());
        }
        return msg_id;
    }

    public static void main(String[] args) {
        String s = testSendSMSCode("15953321059");
        System.out.println("手机验证码："+s);
    }

}
